import React from "react";
import ReactDom from "react-dom/client";
import "./index.css";
/**
 *
 * 全局消息提示组件
 */

// 需要扩展window对象类型
declare global {
  interface Window {
    // 大写Window
    showMessage: (msg: string) => void;
  }
}

interface Itesm {
  id?: number;
  root: ReactDom.Root;
  dom: HTMLDivElement;
}

// 组件
export const Message = (props: { msg: string }) => {
  return <div>{props.msg}</div>;
};

// 消息队列
const queue: Itesm[] = [];

window.showMessage = (msg: string) => {
  const div = document.createElement("div");
  div.className = "message";
  div.style.position = "fixed";
  div.style.left = "50%";
  div.style.transform = "translateX(-50%)";
  // 高度
  div.style.top = `${queue.length * 50}px`;
  div.innerText = msg;
  // 渲染组件
  const root = ReactDom.createRoot(div);
  root.render(<Message msg={msg} />);
  document.body.appendChild(div);

  // 添加到队列
  queue.push({
    id: queue.length,
    root,
    dom: div,
  });

  // 定时关闭
  setTimeout(() => {
    document.body.removeChild(div);
    const index = queue.findIndex((item) => item.dom === div);
    queue.splice(index, 1);
    root.unmount(); // 卸载组件
  }, 2000);
};
